<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\Keywords;
use Hyperf\Context\Context;
use Hyperf\Rpc\Context as RpcContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class JsonRpcContext implements MiddlewareInterface
{
    protected ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        //获取json-rpc带过来的上下文
        $context = $this->container->get(RpcContext::class)->getData();
        //将lang放入到上下文中，用于多语言的支持
        Context::set(Keywords::LANG,$context[Keywords::LANG]??\Hyperf\Config\config("translation.locale"));
        //将请求id放入到上下文中
        Context::set(Keywords::REQUEST_ID,$context[Keywords::REQUEST_ID]??uniqid());

        return $handler->handle($request);
    }
}
